#include <sys/stat.h>

#include <dlfcn.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include <libcapsicum.h>


typedef int (*signature)(const char*, struct stat*);

int stat(const char *path, struct stat *sb)
{
	struct lc_fdlist *fds = lc_fdlist_global();

	int i;
	for(i = 0; ;)
	{
		char *subsystem = "org.freebsd.capsh";
		char *classname = "FileArgument";
		char *name;
		int fd;

		if (lc_fdlist_lookup(fds, subsystem, classname, &name, &fd, &i) < 0)
			break;

		if (strncmp(path, name, strlen(path)) == 0)
			return fstat(fd, sb);
	}


	/* We didn't find the file in our FD list. If we're in a sandbox, die. */
	if(ld_insandbox())
	{
		errno = ENOENT;
		return (-1);
	}
	/* If we're not in a sandbox, try the normal stat(2). */
	else
	{
		signature real_stat = (signature) dlfunc(RTLD_NEXT, "stat");
		return real_stat(path, sb);
	}
}

int _stat(const char *path, struct stat* sb)
{
	return stat(path, sb);
}

